package com.android.duininsuoai.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.duininsuoai.R;
import com.android.duininsuoai.activity.BaseObject;
import com.android.duininsuoai.activity.mine.BuyTicketActivity;
import com.android.duininsuoai.activity.mine.LoginActivity;
import com.android.duininsuoai.adapt.MytimeViewHolder;
import com.android.duininsuoai.model.MainTabData;
import com.android.duininsuoai.model.auction.AuctionActivityData;
import com.android.duininsuoai.model.auction.AuctionActivitySendData;
import com.android.duininsuoai.model.auction.AuctionBannerData;
import com.android.duininsuoai.model.auction.AuctionRecentlyOrder;
import com.android.duininsuoai.model.auction.AuctionRecentlyOrderCallback;
import com.android.duininsuoai.model.auction.AuctionResultData;
import com.android.duininsuoai.model.auction.Auction_JoinBackData;
import com.android.duininsuoai.model.auction.Auction_JoinSendData;
import com.android.duininsuoai.model.auction.Auction_NavData;
import com.android.duininsuoai.model.auction.UpdateAuctionBean;
import com.android.duininsuoai.model.detail.Banner;
import com.android.duininsuoai.model.member.LoginResultData;
import com.android.duininsuoai.model.member.LoginResultDataCallback;
import com.android.duininsuoai.service.WebSocketService;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.LoginState;
import com.android.duininsuoai.utils.MyLog;
import com.android.duininsuoai.utils.ObjectUtils;
import com.android.duininsuoai.view.AutoVerticalScrollTextView;
import com.android.duininsuoai.view.group.ViewPagerIndicator;
import com.android.duininsuoai.view.recycleview.CustomLoadMoreView;
import com.android.duininsuoai.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.android.duininsuoai.R.id.listView;


/**
 * App首页
 */

public class Fragment1 extends Fragment implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.click_resetnetwork_refresh)
    TextView clickResetnetworkRefresh;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.main_top_title)
    TextView mainTopTitle;
    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.custom_ll)
    LinearLayout custom_ll;
    private ViewPager bannerpager;
    private AutoVerticalScrollTextView auction_topline_tv;
    private ViewPagerIndicator viewPagerIndicator1;
    private NestFullListView main_fragment_grid_sort1;
    private View auctioning_v;
    private View newerprefecture_v;
    private View mine_auction_v;
    private RelativeLayout auctioning_lt;
    private RelativeLayout newerprefecture_lt;
    private RelativeLayout mine_auction_lt;
    private ArrayList<MainTabData> griddata1 = new ArrayList<>();
    private ArrayList<Banner.Bannerdata> Bannerlist = new ArrayList<>();
    private Auction_NavData navData;
    private WebSocketService service;
    private BroadcastReceiver mBroadcastReceiver;
    private View view;
    private FragmentActivity mcontext;
    private boolean networkConnected;
    private LayoutInflater inflater;
    private AdaptList adapter;
    private StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    private int page = 1;
    private Message message,message2,message3,message4;
    private View fragment_head;
    private LinearLayout type_ll;
    private int lastOffset,lastPosition;
    private int y;
    private int[] location = new int[2];
    private int mid;
    private String token;
    private HashMap<String,MytimeViewHolder> myViewHolderList = new HashMap<>();
    private HashMap<String,Boolean> isStartMap = new HashMap<>();
    private HashMap<String,UpdateAuctionBean> updateBean = new HashMap<>();
    private HashMap<String,UpdateAuctionBean> lastperiodBean = new HashMap<>();
    private AuctionBannerData auctionBannerData;
    private Auction_JoinSendData auction_joinSendData = new Auction_JoinSendData();
    private AuctionActivitySendData auctionActivitySendData = new AuctionActivitySendData();
    private AuctionActivityData auctionactivitydata;
    private Auction_JoinBackData auction_joinBackData = new Auction_JoinBackData();
    private AuctionResultData auctionResultData = new AuctionResultData();
    private String auction_style = "auctioning";
    private boolean isRunning = false;
    private int count_topline=0;
    private String[] auction_toplines = new String[3];
    private Gson  gson = new Gson();
    private String gsonstring="";
    private ArrayList<AuctionActivityData.ListBean> listdata ;
    private ArrayList<AuctionActivityData.ListBean> temporaryf1_listdata = new ArrayList<>();
    private String get_banner ="{\"type\":\"get_banner\"}";
    private String get_menus ="{\"type\":\"get_menus\"}";





    protected void initData() {
        myViewHolderList.clear();
        temporaryf1_listdata.clear();
        broadcastReceive();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            auctionActivitySendData.setType("get_auctions");
            auctionActivitySendData.setPage(page);
            auctionActivitySendData.setPer_page(10);
            switch (auction_style)
            {
                case "auctioning":
                    break;
                case "mine_auctioning":
                    String mid = LoginState.getInstance().getid(mcontext);
                    auctionActivitySendData.setMid(Integer.parseInt(mid));
                    break;
                case  "for_new":
                    auctionActivitySendData.setFor_new(0);
                    break;
            }
            gsonstring = gson.toJson(auctionActivitySendData);
            service.sendMsg(gsonstring);

        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
        isRunning = true;
        handler1.postDelayed(mRunnable,100);
        //更新拼团快报
        new Thread() {
            @Override
            public void run() {
                while (isRunning) {
                    SystemClock.sleep(3000);
                    handler2.sendEmptyMessage(1);
                }
            }
        }.start();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_fragment1, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        String appName = getResources().getString(R.string.app_name);
        mainTopTitle.setText(appName);
        mainTopTitle.setTextColor(Color.parseColor("#ffffff"));
        mainTopBg.setBackgroundColor(Color.parseColor("#FF2741"));
        initUI();
        initDatadata();
        initData();
        //GetDataBanner();
        //GetDataListData(page);
        return view;
    }

    @Override
    public void onResume()
    {
        super.onResume();
        if(!LoginState.getInstance().getid(mcontext).equals("")&&LoginState.getInstance().getid(mcontext)!=null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
            token = LoginState.getInstance().getUserInfo(mcontext,2);
           // SetDou();

        }

    }

    @Override
        public void onLoadMoreRequested() {
        page = page + 1;
        auctionActivitySendData.setType("get_auctions");
        auctionActivitySendData.setPage(page);
        auctionActivitySendData.setPer_page(10);
        switch (auction_style)
        {
            case "auctioning":
                break;
            case "mine_auctioning":
                String mid = LoginState.getInstance().getid(mcontext);
                auctionActivitySendData.setMid(Integer.parseInt(mid));
                break;
            case  "for_new":
                auctionActivitySendData.setFor_new(0);
                break;
        }
        gsonstring = gson.toJson(auctionActivitySendData);
        service.sendMsg(gsonstring);
    }

    private void initDatadata() {
        GetRecentlyQuery();

        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    myViewHolderList.clear();
                    temporaryf1_listdata.clear();
                    listdata.clear();
                    service.sendMsg(get_banner);
                    auctionActivitySendData.setType("get_auctions");
                    auctionActivitySendData.setPage(page);
                    auctionActivitySendData.setPer_page(10);
                    switch (auction_style)
                    {
                        case "auctioning":
                            break;
                        case "mine_auctioning":
                            String mid = LoginState.getInstance().getid(mcontext);
                            auctionActivitySendData.setMid(Integer.parseInt(mid));
                            break;
                        case  "for_new":
                            auctionActivitySendData.setFor_new(0);
                            break;
                    }
                    gsonstring = gson.toJson(auctionActivitySendData);
                    service.sendMsg(gsonstring);
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
//        griddata1.clear();
//        griddata1.add(new MainTabData("购劵", "1", R.mipmap.recharge));
//        griddata1.add(new MainTabData("晒单", "2", R.mipmap.shareorder));
//        griddata1.add(new MainTabData("直购", "3", R.mipmap.turntable));
//        griddata1.add(new MainTabData("帮助", "4", R.mipmap.help));
        //分类+快报
        main_fragment_grid_sort1.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_grid_fragment_sort, griddata1) {
            @Override
            public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                holder.setText(R.id.item_grid_fragment_sort_tv, testBean.getName());
                holder.setImageResource(R.id.item_grid_fragment_sort_img, testBean.getThumb());
            }
        });
        main_fragment_grid_sort1.setOnItemClickListener(new MainSortStartTo(griddata1));

    }
    private void initUI() {
        fragment_head = inflater.inflate(R.layout.main_fragment1_head_banner, null, false);
        type_ll = (LinearLayout)fragment_head.findViewById(R.id.type_ll);
        bannerpager = (ViewPager) fragment_head.findViewById(R.id.bannerpager_fragment);
        viewPagerIndicator1 = (ViewPagerIndicator) fragment_head.findViewById(R.id.viewPagerIndicator1);
        main_fragment_grid_sort1 = (NestFullListView) fragment_head.findViewById(R.id.main_fragment_grid_sort1);
       auction_topline_tv = ( AutoVerticalScrollTextView )fragment_head.findViewById(R.id.auction_topline_tv);
        auctioning_v = (View) fragment_head.findViewById(R.id.auctioning_v);
        newerprefecture_v = (View) fragment_head.findViewById(R.id.newerprefecture_v);
        mine_auction_v = (View) fragment_head.findViewById(R.id.mine_auction_v);
        auctioning_lt = (RelativeLayout) fragment_head.findViewById(R.id.auctioning_lt);
        newerprefecture_lt = (RelativeLayout) fragment_head.findViewById(R.id.newerprefecture_lt);
        mine_auction_lt = (RelativeLayout) fragment_head.findViewById(R.id.mine_auction_lt);

        auctioning_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myViewHolderList.clear();
                temporaryf1_listdata.clear();
                listdata.clear();
                auctioning_v.setVisibility(View.VISIBLE);
                newerprefecture_v.setVisibility(View.INVISIBLE);
                mine_auction_v.setVisibility(View.INVISIBLE);
                page=1;
                auction_style ="auctioning";
                auctionActivitySendData.setType("get_auctions");
                auctionActivitySendData.setPage(page);
                auctionActivitySendData.setPer_page(10);
                switch (auction_style)
                {
                    case "auctioning":
                        break;
                    case "mine_auctioning":
                        String mid = LoginState.getInstance().getid(mcontext);
                        auctionActivitySendData.setMid(Integer.parseInt(mid));
                        break;
                    case  "for_new":
                        auctionActivitySendData.setFor_new(0);
                        break;
                }
                gsonstring = gson.toJson(auctionActivitySendData);
                service.sendMsg(gsonstring);

            }
        });
        newerprefecture_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myViewHolderList.clear();
                temporaryf1_listdata.clear();
                listdata.clear();
                auctioning_v.setVisibility(View.INVISIBLE);
                newerprefecture_v.setVisibility(View.VISIBLE);
                mine_auction_v.setVisibility(View.INVISIBLE);
                page=1;
                auction_style ="for_new";
                auctionActivitySendData.setType("get_auctions");
                auctionActivitySendData.setPage(page);
                auctionActivitySendData.setPer_page(10);
                switch (auction_style)
                {
                    case "auctioning":
                        break;
                    case "mine_auctioning":
                        String mid = LoginState.getInstance().getid(mcontext);
                        auctionActivitySendData.setMid(Integer.parseInt(mid));
                        break;
                    case  "for_new":
                        auctionActivitySendData.setFor_new(0);
                        break;
                }
                gsonstring = gson.toJson(auctionActivitySendData);
                service.sendMsg(gsonstring);

            }
        });
        mine_auction_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myViewHolderList.clear();
                temporaryf1_listdata.clear();
                listdata.clear();
                auctioning_v.setVisibility(View.INVISIBLE);
                newerprefecture_v.setVisibility(View.INVISIBLE);
                mine_auction_v.setVisibility(View.VISIBLE);
                page=1;
                auction_style ="mine_auctioning";
                auctionActivitySendData.setType("get_auctions");
                auctionActivitySendData.setPage(page);
                auctionActivitySendData.setPer_page(10);
                switch (auction_style)
                {
                    case "auctioning":
                        break;
                    case "mine_auctioning":
                        String mid = LoginState.getInstance().getid(mcontext);
                        auctionActivitySendData.setMid(Integer.parseInt(mid));
                        break;
                    case  "for_new":
                        auctionActivitySendData.setFor_new(0);
                        break;
                }
                gsonstring = gson.toJson(auctionActivitySendData);
                service.sendMsg(gsonstring);

            }
        });
        adapter = new AdaptList(mcontext, null, "0");
        //  adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        adapter.addHeaderView(fragment_head);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
//        ((TextView) view.findViewById(R.id.scroll_total)).setText();
        mRecyclerView.GetToTop((ImageView) view.findViewById(R.id.top), 1);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.rightnow_openteam:
                        if (LoginState.getInstance().isLogin(mcontext)) {
                            auction_joinSendData.setType("join_auction");
                            auction_joinSendData.setId(Integer.parseInt(adapter.getData().get(position).getId()));
                            auction_joinSendData.setMid(mid);
                            auction_joinSendData.setToken(token);
                            gsonstring = gson.toJson(auction_joinSendData);
                            service.sendMsg(gsonstring);
                        }
                        else
                        {
                            startActivity(new Intent(mcontext, LoginActivity.class));
                        }
                        break;

                }
                return false;
            }
        });
    }

    /**
     * 分类跳转
     */

    class MainSortStartTo implements NestFullListView.OnItemClickListener {
        ArrayList<MainTabData> griddata;

        public MainSortStartTo(ArrayList<MainTabData> griddata) {
            this.griddata = griddata;
        }

        @Override
        public void onItemClick(NestFullListView nestFullListView, View view, int position) {
            switch (griddata.get(position).getId()) {
                case "1":
                    Intent intent_voucher = new Intent(mcontext,BuyTicketActivity.class);
                    startActivity(intent_voucher);
                    break;
                case "2":

                    break;
                case "3":
                    Intent intent_address = new Intent(mcontext, BaseObject.class);
                    intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, griddata.get(position).getName());
                    startActivity(intent_address);
                    break;
                case "4":
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 轮播图销毁开启
     */

    @Override
    public void onStart() {
        super.onStart();

        viewPagerIndicator1.setVisible(true);
    }


    @Override
    public void onPause() {
        super.onPause();

        viewPagerIndicator1.setVisible(false);
    }
    @OnClick({R.id.click_resetnetwork_refresh})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                myViewHolderList.clear();
                temporaryf1_listdata.clear();
                service.sendMsg(get_banner);
                page = 1;
                auctionActivitySendData.setType("get_auctions");
                auctionActivitySendData.setPage(page);
                auctionActivitySendData.setPer_page(10);
                switch (auction_style)
                {
                    case "auctioning":
                        break;
                    case "mine_auctioning":
                        String mid = LoginState.getInstance().getid(mcontext);
                        auctionActivitySendData.setMid(Integer.parseInt(mid));
                        break;
                    case  "for_new":
                        auctionActivitySendData.setFor_new(0);
                        break;
                }
                gsonstring = gson.toJson(auctionActivitySendData);
                service.sendMsg(gsonstring);
                break;

        }
    }
    //设置广播监听
    private void broadcastReceive()
    {
        service = WebSocketService.getInstance();
        service.sendMsg(get_banner);
         service.sendMsg(get_menus);
        mBroadcastReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //更新竞买返回消息
                if(action.equals(WebSocketService.ACTION_NOT)){
                    Intent intents = mcontext.getIntent();
                    auctionResultData = (AuctionResultData)intent.getBundleExtra("bundle").getSerializable("AuctionResult");
                    if(auctionResultData!=null)
                    {
                        if(!auction_style.equals("mine_auctioning"))
                        {
                            DealWithResult();
                        }
                    }
                }

                if(action.equals(WebSocketService.ACTION_BANNER))
                {
                    auctionBannerData = (AuctionBannerData)intent.getBundleExtra("bundle1").getSerializable("AuctionBanner");
                    GetBanner();
                }
                //更新商品列表
                if(action.equals(WebSocketService.ACTION_AUCTION))
                {

                    boolean isUpdateUsername =false;
                    auctionactivitydata = (AuctionActivityData) intent.getBundleExtra("bundle2").getSerializable("AuctionGetAuctions");
                    if(auctionactivitydata.getList()!=null&&auctionactivitydata.getList().size()>0) {
                        int midd=0;
//                        if(auctionactivitydata.getList().get(0).getMid()!=null)
//                        {
//                            midd = Integer.parseInt(auctionactivitydata.getList().get(0).getMid());
//                        }
//                        if(midd>0)
//                        {
//                            isUpdateUsername =true;
//                        }
                        listdata = new ArrayList<>();
                        if(page==1)
                        {
                            temporaryf1_listdata.clear();
                        }
                        for (int i = 0; i < auctionactivitydata.getList().size(); i++) {
//                            if(isUpdateUsername)
//                            {
////                                   if (auctionactivitydata.getList().get(i).getUsername() != null && !auctionactivitydata.getList().get(i).getUsername().equals(""))
////                                   {
////                                       currentlyUser.put(auctionactivitydata.getList().get(i).getId(), auctionactivitydata.getList().get(i).getUsername());
////                                   }
//                            }
//                            else {

                                temporaryf1_listdata.add(new AuctionActivityData.ListBean(AuctionActivityData.ListBean.THREE, auctionactivitydata.getList().get(i).getId()
                                        , auctionactivitydata.getList().get(i).getPeriod(), auctionactivitydata.getList().get(i).getTitle()
                                        , auctionactivitydata.getList().get(i).getThumb(), auctionactivitydata.getList().get(i).getPrice()
                                        , auctionactivitydata.getList().get(i).getTime() * 1000, auctionactivitydata.getList().get(i).getStart() * 1000
                                        , auctionactivitydata.getList().get(i).getMid(), auctionactivitydata.getList().get(i).getUsername()));
                                listdata.add(new AuctionActivityData.ListBean(AuctionActivityData.ListBean.THREE, auctionactivitydata.getList().get(i).getId()
                                        , auctionactivitydata.getList().get(i).getPeriod(), auctionactivitydata.getList().get(i).getTitle()
                                        , auctionactivitydata.getList().get(i).getThumb(), auctionactivitydata.getList().get(i).getPrice()
                                        , auctionactivitydata.getList().get(i).getTime() * 1000, auctionactivitydata.getList().get(i).getStart() * 1000
                                        , auctionactivitydata.getList().get(i).getMid(), auctionactivitydata.getList().get(i).getUsername()));
                                if (auctionactivitydata.getList().get(i).getStart() != 0)
                                {
                                    isStartMap.put(auctionactivitydata.getList().get(i).getId(), true);
                                }
                                else {
                                    isStartMap.put(auctionactivitydata.getList().get(i).getId(), false);
                                }
                            updateBean.put(auctionactivitydata.getList().get(i).getId(),new UpdateAuctionBean());
                            lastperiodBean.put(auctionactivitydata.getList().get(i).getId(),new UpdateAuctionBean());
                           // }
                        }
//                        if(isUpdateUsername)
//                        {
//                            //  handler1.post(mRunnable3);
//                        }
//                        else
//                        {

                            AdapterListData();
                        //}
                    }
                else
                {
                    adapter.loadMoreEnd();
                }

            }
                //更新商品竞买时间，价格，出价人
                if(action.equals(WebSocketService.ACTION_JOINBACK))
                {
                    auction_joinBackData = (Auction_JoinBackData)intent.getBundleExtra("bundle3").getSerializable("AuctionJoinBack");
                    String code = auction_joinBackData.getCode();
                    if(code!=null&&!code.equals(""))
                    {
                        if(Integer.parseInt(code)>0)
                        {
                            ObjectUtils.toast(mcontext,auction_joinBackData.getMsg());
                        }
                    }

                    if(temporaryf1_listdata!=null) {
                        boolean isupdateusername = false;
                        for (int i = 0; i < temporaryf1_listdata.size(); i++) {
                            int id = Integer.parseInt(temporaryf1_listdata.get(i).getId());
                            if (auction_joinBackData.getId() == id) {
                                if(auction_joinBackData.getUsername()!=null&&auction_joinBackData.getPrice()>0)
                                {
                                    isupdateusername = true;
                                    UpdateAuctionBean update = new UpdateAuctionBean();
                                    update.setUsername(auction_joinBackData.getUsername());
                                    update.setPrice(auction_joinBackData.getPrice());
                                    updateBean.put(temporaryf1_listdata.get(i).getId(),update);
                                    if(auction_joinBackData.getTime()>0)
                                    {
                                        temporaryf1_listdata.get(i).setTime(auction_joinBackData.getTime() * 1000);
                                        break;
                                    }
                                    break;
                                }
                            }
                        }
                        if(isupdateusername)
                        {
                            handler1.post(mRunnable3);
                        }
                    }
                }
//                   if(action.equals(WebSocketService.ACTION_Nav))
//                   {
//                       navData= (Auction_NavData) intent.getBundleExtra("bundle2").getSerializable("AuctionNav");
//                       GetMenus();
//                   }

            }
        };
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(WebSocketService.ACTION_NOT);
        myIntentFilter.addAction(WebSocketService.ACTION_BANNER);
        myIntentFilter.addAction(WebSocketService.ACTION_AUCTION);
        myIntentFilter.addAction(WebSocketService.ACTION_JOINBACK);
        // myIntentFilter.addAction(WebSocketService.ACTION_Nav);
        //注册广播
        mcontext.registerReceiver(mBroadcastReceiver, myIntentFilter);


    }
    /**
     * 获取最新成交消息
     */
    private void GetRecentlyQuery()
    {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address =  ConstantsUrl.domain+ConstantsUrl.ACUTIONRECENTLYORDER;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> map = new HashMap<>();
            map.put("page","1");
            map.put("size","3");
            HttpUtils.post(address,map, new AuctionRecentlyOrderCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.toast(mcontext,e.getMessage());
                        }

                        @Override
                        public void onResponse(AuctionRecentlyOrder response, int id) {

                            if (response.getCode() == 0) {
                                if(response.getData().getList()!=null) {
                                    int size =3;
                                    if(response.getData().getList().size()<3)
                                    {
                                       size = response.getData().getList().size();
                                    }
                                    for (int i = 0; i < size; i++) {
                                        String content = "恭喜" + response.getData().getList().get(i).getUsername() + "以"
                                                + response.getData().getList().get(i).getPrice() + "拍得"
                                                + response.getData().getList().get(i).getReturns_score();
                                        auction_toplines[i] = content;
                                    }
                                    auction_topline_tv.setText(auction_toplines[0]);
                                }
                                else
                                {
                                    for(int i=0;i<3;i++)
                                    {
                                        auction_toplines[i] = "暂无竞买消息";
                                    }
                                }
                            }
                            else
                            {
                                for(int i=0;i<3;i++)
                                {
                                    auction_toplines[i] = "暂无竞买消息";
                                }
                              }
                        }
            }

            );
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }
    /**
     * 获取菜单
     */
    private void GetMenus()
    {
        griddata1.clear();
        if(navData.getList()!=null) {
            griddata1.add(new MainTabData(navData.getList().get(0).getTitle(), "1",navData.getList().get(0).getSrc()));
            griddata1.add(new MainTabData(navData.getList().get(0).getTitle(), "2",navData.getList().get(0).getSrc()));
            griddata1.add(new MainTabData(navData.getList().get(0).getTitle(), "3",navData.getList().get(0).getSrc()));
            griddata1.add(new MainTabData(navData.getList().get(0).getTitle(), "4",navData.getList().get(0).getSrc()));
            //分类+快报
            main_fragment_grid_sort1.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_grid_fragment_sort, griddata1) {
                @Override
                public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                    holder.setText(R.id.item_grid_fragment_sort_tv, testBean.getName());
                    ImageView v = holder.getView(R.id.item_grid_fragment_sort_img);
                    ObjectUtils.photo2(mcontext,testBean.getSrc(),v);
                }
            });
            main_fragment_grid_sort1.setOnItemClickListener(new MainSortStartTo(griddata1));
        }
    }
    /**
     * 获取轮播图
     */
   private void GetBanner()
   {
       Bannerlist.clear();

       if(auctionBannerData.getList()!=null) {
           mRefreshLayout.setRefreshing(false);
           ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
           for (int i = 0; i < auctionBannerData.getList().size(); i++) {
               Banner.Bannerdata data = new Banner.Bannerdata();
               data.setThumb(auctionBannerData.getList().get(i).getSrc());
               data.setLink("");
               data.setPath("");
               Bannerlist.add(data);
           }
           //轮播图
           if(Bannerlist!=null) {
               viewPagerIndicator1.autoScroll(getChildFragmentManager(), bannerpager, 1);
               viewPagerIndicator1.setViewPager(Bannerlist);
               viewPagerIndicator1.setNotifyDataSetChanged();
           }
       }
   }
    /**
     * 处理竞买返回通知消息
     */
    private void DealWithResult()
    {
        /**
         * 竞买返回通知重开
         */
        if(auctionResultData.getTime()>0&&auctionResultData.getStart()>0)
        {
            /**
             * 更新重开的商品时间
             */
                if (temporaryf1_listdata != null) {
                    for (int i = 0; i < temporaryf1_listdata.size(); i++) {
                        int id = Integer.parseInt(temporaryf1_listdata.get(i).getId());
                        if (auctionResultData.getId() .equals( id)) {
                            temporaryf1_listdata.get(i).setTime(auctionResultData.getTime() * 1000);
                            temporaryf1_listdata.get(i).setStart(auctionResultData.getStart() * 1000);
                            isStartMap.put(temporaryf1_listdata.get(i).getId(), true);
                            break;
                        }
                    }
                }
            /**
             * 有人中拍时
             */
                    if(auctionResultData.getMid()>0)
                    {
                        /**
                         * 头条
                         */
                        String content = "恭喜" +auctionResultData.getUsername()+"以"
                                +auctionResultData.getPrice()+"拍得"
                                +auctionResultData.getTitle();
                        for(int i =0;i<2;i++)
                        {
                            auction_toplines[i] = auction_toplines[i+1];
                        }
                        auction_toplines[2] = content;
                        /**
                         * 更新上期中拍商品活动状态和数据
                         */
                        UpdateAuctionBean update = new UpdateAuctionBean();
                        update.setUsername(auctionResultData.getUsername());
                        update.setIspass_in(false);
                        lastperiodBean.put(auctionResultData.getId()+"",update);
                        handler1.post(mRunnable4);
                    }
                    /**
                     * 无人中拍时
                     */
                  else
                    {
                        /**
                         * 更新上期流拍商品活动状态
                         */
                        UpdateAuctionBean update = new UpdateAuctionBean();
                        update.setIspass_in(true);
                        lastperiodBean.put(auctionResultData.getId()+"",update);
                        handler1.post(mRunnable4);
                    }
        }
        /**
         * 竞买返回通知不重开
         */
        else
        {
            /**
             *
             */
//           if(auction_style.equals("mine_auctioning")) {
//               if (listdata != null) {
//                   for (int i = 0; i < listdata.size(); i++) {
//                       int id = Integer.parseInt(listdata.get(i).getId());
//                       if (auctionResultData.getId() == id) {
//                           listdata.remove(i);
//                           break;
//                       }
//                   }
//               }
//               if (myViewHolderList.containsKey(auctionResultData.getId())) {
//                   myViewHolderList.remove(auctionResultData.getId());
//               }
//           }
            /**
             * 有人中拍时
             */
            if(auctionResultData.getMid()>0)
            {
                /**
                 * 头条
                 */
                String content = "恭喜" +auctionResultData.getUsername()+"以"
                        +auctionResultData.getPrice()+"拍得"
                        +auctionResultData.getTitle();
                for(int i =0;i<2;i++)
                {
                    auction_toplines[i] = auction_toplines[i+1];
                }
                auction_toplines[2] = content;
                /**
                 * 更新上期中拍商品活动状态和数据
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setUsername(auctionResultData.getUsername());
                update.setIspass_in(false);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
            /**
             * 无人中拍时
             */
            else
            {
                /**
                 * 更新上期流拍商品活动状态
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setIspass_in(true);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
        }
    }

    /**
     * 适配商品列表
     */
    private void AdapterListData()
    {

            mRefreshLayout.setRefreshing(false);
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            if (page == 1) {
                adapter.setNewData(listdata);
            } else {
                adapter.addData(listdata);
                adapter.loadMoreComplete();
            }

        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setAdapter(adapter);
         adapter.notifyDataSetChanged();
            if (auctionactivitydata.getList().size() < 10 ) {
                adapter.loadMoreComplete();
                adapter.loadMoreEnd();
            }

    }

    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    adapter.notifyTimeData();
                    break;
                case 2:
                    adapter.notifyDataSetChanged();
                    break;
                case 3:
                    adapter.notifyUsernameData();
                    break;
                case 4:
                    adapter.notifyLastPeriod();
                    break;
                case 5:
                    if(mRecyclerView.getLayoutManager() != null && lastPosition >= 0) {
                        ((StaggeredGridLayoutManager) mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);

                    }
                    break;
            }
        }
    };
    //更新快报
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    auction_topline_tv.next();
                    count_topline++;
                    auction_topline_tv.setText(auction_toplines[count_topline%3]);
                    break;

            }
        }
    };

    //更新上一期活动是否流拍
    private Runnable mRunnable4 = new Runnable() {
        @Override
        public void run() {
            if (null == message4) {
                message4 = new Message();
            } else {
                message4 = Message.obtain();
            }
            message4.what = 4;
            //发送信息给handler
            handler1.sendMessage(message4);
        }
    };
    //更新当前出价和竞拍人
    private Runnable mRunnable3 = new Runnable() {
        @Override
        public void run() {
            if (null == message3) {
                message3 = new Message();
            } else {
                message3 = Message.obtain();
            }
            message3.what = 3;
            //发送信息给handler
            handler1.sendMessage(message3);
        }
    };
    //更新商品是否过期
    private Runnable mRunnable2 = new Runnable() {
        @Override
        public void run() {
            if (null == message2) {
                message2 = new Message();
            } else {
                message2 = Message.obtain();
            }
            message2.what = 2;
            //发送信息给handler
            handler1.sendMessage(message2);
        }
    };
    //更新商品时间
    private Runnable mRunnable = new Runnable(){

        @Override
        public void run() {
            if( temporaryf1_listdata!=null) {
                for (int i = 0; i <  temporaryf1_listdata.size(); i++) {

                    int time =  temporaryf1_listdata.get(i).getTime();
                    int start =  temporaryf1_listdata.get(i).getStart();

                    if (start > 0) {
                        start = start - 40;
                        temporaryf1_listdata.get(i).setStart(start);
                    }
                    if (time > 0) {
                        time = time - 40;
                        temporaryf1_listdata.get(i).setTime(time);

                    }
                }
            }
            if (null == message) {
                message = new Message();
            } else {
                message = Message.obtain();
            }
            message.what = 1;
            //发送信息给handler
            handler1.sendMessage(message);
            //每40豪秒重启一下线程
           handler1.postDelayed(mRunnable, 40);
        }
    };


    public class AdaptList extends BaseMultiItemQuickAdapter<AuctionActivityData.ListBean,MytimeViewHolder> {
        private String type;
        private FragmentActivity mcontext;
        private int limitposition;
        public ArrayList<AuctionActivityData.ListBean> data = new ArrayList();
        public AdaptList(FragmentActivity context, ArrayList<AuctionActivityData.ListBean> data, String type) {
            super(data);
            this.data=data;
            this.mcontext = context;
            this.type = type;
            addItemType(AuctionActivityData.ListBean.THREE, R.layout.item_grid_aishangmainpage);
        }



        @Override
        protected void convert(MytimeViewHolder holder,AuctionActivityData.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case AuctionActivityData.ListBean.THREE:
                    if(!(myViewHolderList.containsKey(mainlistdata.getId()))) {
                        myViewHolderList.put(mainlistdata.getId(), holder);
                        holder.setTime_position(holder.getLayoutPosition());
                        //判断list里面是否含有该holder，没有就增加
                        //因为list已经持有holder的引用，所有数据自动会改变
                        int time = mainlistdata.getTime();
                        String minute = String.format("%02d", time / 1000 / 60);
                        String second = String.format("%02d", time / 1000 % 60);
                        String millsecond = "00";
                        if (time % 1000 == 0) {
                            millsecond = String.format("%02d", 99);
                        } else {
                            millsecond = String.format("%02d", time % 1000 / 40 * 4);
                        }
                        holder.setText(R.id.kill_millsecond, millsecond);
                        holder.setText(R.id.kill_minute, minute);
                        holder.setText(R.id.kill_second, second);
                        ObjectUtils.photo2(mContext, mainlistdata.getThumb(), ((ImageView) holder.getView(R.id.item_grid_aishang_img)));
                        // holder.setText(R.id.rightnow_phone, mainlistdata.getUsername());
                        holder.setText(R.id.item_rightnow_price, "当前价: ￥" + mainlistdata.getPrice());
                        holder.setText(R.id.item_grid_detail_like_title, mainlistdata.getTitle());
                        holder.addOnClickListener(R.id.rightnow_openteam);
                    }
                    break;
            }
        }
        //更新当前出价竞拍人
        public void notifyUsernameData() {
            if(listdata!=null) {
                for (int i = 0; i <  temporaryf1_listdata.size(); i++) {
                    String id =  temporaryf1_listdata.get(i).getId();
                    if (myViewHolderList.containsKey(id)) {
                        if(updateBean.get(id).getPrice()>0) {
                            myViewHolderList.get(id).getItem_rightnow_ll().setVisibility(View.VISIBLE);
                            myViewHolderList.get(id).getItem_lastperiod_failed().setVisibility(View.GONE);
                            myViewHolderList.get(id).getItem_lastperiod_ll().setVisibility(View.GONE);
                          //  myViewHolderList.get(id).getItem_rightnow_person().setText(updateBean.get(id).getUsername());
                            myViewHolderList.get(id).getItem_rightnow_price().setText("当前价: ￥" + updateBean.get(id).getPrice());
                        }
                    }
                }
            }
        }
        //更新上期商品活动是否流拍
        public void notifyLastPeriod() {
            if(listdata!=null) {
                for (int i = 0; i <  temporaryf1_listdata.size(); i++) {
                    String id = temporaryf1_listdata.get(i).getId();
                    if (myViewHolderList.containsKey(id)) {
                        if(lastperiodBean.get(id).ispass_in())
                        {
                            myViewHolderList.get(id).getItem_rightnow_ll().setVisibility(View.GONE);
                            myViewHolderList.get(id).getItem_lastperiod_failed().setVisibility(View.VISIBLE);
                            myViewHolderList.get(id).getItem_lastperiod_ll().setVisibility(View.GONE);
                        }
                        else
                        {
                            myViewHolderList.get(id).getItem_rightnow_ll().setVisibility(View.GONE);
                            myViewHolderList.get(id).getItem_lastperiod_failed().setVisibility(View.GONE);
                            myViewHolderList.get(id).getItem_lastperiod_ll().setVisibility(View.VISIBLE);
                            myViewHolderList.get(id).getItem_lastperiod_person().setText(lastperiodBean.get(id).getUsername());
                        }
                    }
                }
            }
        }
        //更新全部商品时间
                    public void notifyTimeData(){

                        if( temporaryf1_listdata!=null) {

                            /**
                             * 如果是我在拍的界面，移除倒计时归零的的商品
                             */
                            if (auction_style.equals("mine_auctioning")) {
                                for (int i = 0; i <  temporaryf1_listdata.size(); i++) {
                                    int time =  temporaryf1_listdata.get(i).getTime();
                                    int start =  temporaryf1_listdata.get(i).getStart();
                                    if (myViewHolderList.containsKey( temporaryf1_listdata.get(i).getId())) {
                                        boolean isstart = isStartMap.get( temporaryf1_listdata.get(i).getId());
                                        //没有start时间时
                                        if (time > 0 && !isstart) {
                                            myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
                                            myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg_selector);
                                        }//有start时间时
                                        else {

                                            //开始参加竞买
                                            if (isstart && start <= 0) {
                                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
                                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg_selector);
                                            } else {
                                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setEnabled(false);
                                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_gray_bg);
                                            }
                                        }
                                        //只要竞买还没结束
                                        if (time >= 0) {

                                            String minute = String.format("%02d", time / 1000 / 60);
                                            String second = String.format("%02d", time / 1000 % 60);
                                            String millsecond = String.format("%02d", time % 1000 / 40 * 4);
                                            myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getKill_millsecond().setText(millsecond);
                                            myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getKill_minute().setText(minute);
                                            myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getKill_second().setText(second);
                                            if(time==0)
                                            {
                                                myViewHolderList.remove( temporaryf1_listdata.get(i).getId());
                                                temporaryf1_listdata.remove(i);
                                                adapter.notifyDataSetChanged();
                                            }
                                        }
                                    }
                                }
                            } else {
                    for (int i = 0; i <  temporaryf1_listdata.size(); i++) {
                        int time =  temporaryf1_listdata.get(i).getTime();
                        int start =  temporaryf1_listdata.get(i).getStart();
                        if (myViewHolderList.containsKey( temporaryf1_listdata.get(i).getId())) {
                            boolean isstart = isStartMap.get( temporaryf1_listdata.get(i).getId());
                            //没有start时间时
                            if (time > 0 && !isstart) {
                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg_selector);
                            }//有start时间时
                            else {
                                //开始参加竞买
                                if (isstart && start <= 0) {
                                    myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
                                    myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg_selector);
                                } else {
                                    myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setEnabled(false);
                                    myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_gray_bg);
                                }
                            }
                            //只要竞买还没结束
                            if (time >= 0) {

                                String minute = String.format("%02d", time / 1000 / 60);
                                String second = String.format("%02d", time / 1000 % 60);
                                String millsecond = String.format("%02d", time % 1000 / 40 * 4);
                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getKill_millsecond().setText(millsecond);
                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getKill_minute().setText(minute);
                                myViewHolderList.get( temporaryf1_listdata.get(i).getId()).getKill_second().setText(second);

                            }
                        }
                    }
                }
            }
                }

    }

    /**
     * 获取竞买豆
     */
    private void SetDou() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address ="https://jingpai.lnest.cc/api/auction/setMember";
        MyLog.e("主页列表", address);
        HashMap<String,String> map = new HashMap<>();
        map.put("mid",mid+"");
        map.put("coin","10000");
        map.put("free_coin","10000");
        if (networkConnected) {

            HttpUtils.post(address, map, new LoginResultDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(LoginResultData response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        MyLog.e("主页列表d", response.getMsg());
                    }
                }
            });
        } else {

            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络未连接");
            adapter.loadMoreFail();
        }
    }



    @Override
    public void onDestroyView()
    {
       super.onDestroyView();
        view = null;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        MyLog.e("onsdf","ohnfs");
        isRunning=false;
        service = null;
        handler1.removeCallbacks(mRunnable);
        handler2.removeCallbacks(mRunnable4);
        getActivity().unregisterReceiver(mBroadcastReceiver);
        mBroadcastReceiver  = null;
    }

}



